package com.huabo.session;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by Jackie Liu on 2017/4/3.
 */
public class ServletSession implements UserSession {

    public static final String USER_SESSION_KEY = "_user_session_key_";
    public static final String VERIFY_CODE_KEY = "_verify_code_key_";

    @Override
    public boolean setSessionModel(HttpServletRequest request, HttpServletResponse response, SessionModel sessionModel) {
        HttpSession session = request.getSession();
        session.setAttribute(USER_SESSION_KEY, sessionModel);
        return true;
    }

    @Override
    public SessionModel getSessionModel(HttpServletRequest request) {
        HttpSession session = request.getSession();
        SessionModel sessionModel = (SessionModel) session.getAttribute(USER_SESSION_KEY);
        return sessionModel;
    }

    @Override
    public boolean removeSession(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        SessionModel sessionModel = (SessionModel) session.getAttribute(USER_SESSION_KEY);
        if (sessionModel != null) {
            session.removeAttribute(USER_SESSION_KEY);
        }
        session.invalidate();
        return true;
    }

    @Override
    public void resetSessionTime(HttpServletRequest request) {
        //do something
        //在web.xml中配置即可
    }

    @Override
    public void setVerifyCode(HttpServletRequest request, HttpServletResponse response, String verifyCode) {
        HttpSession session = request.getSession();
        session.setAttribute(VERIFY_CODE_KEY, verifyCode);
    }

    @Override
    public String getVerifyCode(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        Object value = session.getAttribute(VERIFY_CODE_KEY);
        return value == null ? null : (String) value;
    }
}
